package com.veinhorn.scrollgalleryview.loader.picasso;

import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.veinhorn.scrollgalleryview.ResourceTable;
import com.veinhorn.scrollgalleryview.loader.MediaLoader;
import ohos.agp.components.Image;
import ohos.app.Context;

/**
 * PicassoImageLoader
 *
 * @author veinhorn
 * @since 2021-05-13
 */
public class PicassoImageLoader implements MediaLoader {
    private static final int RESIZENUM = 100;
    private String mUrl;
    private int mThumbnailWidth = 0;
    private int mThumbnailHeight = 0;

    /**
     * PicassoImageLoader
     *
     * @param url
     */
    public PicassoImageLoader(String url) {
        this.mUrl = url;
    }

    /**
     * PicassoImageLoader
     *
     * @param url
     * @param thumbnailWidth
     * @param thumbnailHeight
     */
    public PicassoImageLoader(String url, int thumbnailWidth, int thumbnailHeight) {
        this.mUrl = url;
        this.mThumbnailWidth = thumbnailWidth;
        this.mThumbnailHeight = thumbnailHeight;
    }

    /**
     * isImage
     *
     * @return boolean
     */
    @Override
    public boolean isImage() {
        return true;
    }

    /**
     * loadMedia
     *
     * @param context
     * @param imageView
     * @param callback
     */
    @Override
    public void loadMedia(Context context, final Image imageView, final MediaLoader.SuccessCallback callback) {
        Picasso.get()
                .load(mUrl)
                .placeholder(ResourceTable.Media_placeholder_image)
                .into(imageView, new ImageCallback(callback));
    }

    /**
     * loadThumbnail
     *
     * @param context
     * @param thumbnailView
     * @param callback
     */
    @Override
    public void loadThumbnail(Context context, final Image thumbnailView, final MediaLoader.SuccessCallback callback) {
        Picasso.get()
                .load(mUrl)
                .resize(mThumbnailWidth == 0 ? RESIZENUM : mThumbnailWidth,
                        mThumbnailHeight == 0 ? RESIZENUM : mThumbnailHeight)
                .placeholder(ResourceTable.Media_placeholder_image)
                .centerInside()
                .into(thumbnailView, new ImageCallback(callback));
    }

    /**
     * ImageCallback
     *
     * @since 2021-05-13
     */
    private static class ImageCallback implements Callback {
        private final MediaLoader.SuccessCallback mCallback;

        ImageCallback(SuccessCallback callback) {
            this.mCallback = callback;
        }

        @Override
        public void onSuccess() {
            mCallback.onSuccess();
        }

        @Override
        public void onError(Exception e) {
        }
    }
}
